var lang;

function loadScript(){
	var funct=function(key,val){
		$(val).attr('id', key);
	}
	$('h2').each(funct)
	
	if($('h2').length==0){
		$('h1').each(funct)
	}
}


function capitalizeEachWord(obj,func){
	/*$(obj).each(function(key,val) { 
		var $obj=$(this);
		$obj.html($obj.html().toLowerCase().capitalize());
	});*/
	if( func!=null && typeof (func)=="function"){
		func();
	}
}


function goto(id){
	//alert(id);
	window.location.hash = '#'+id;
}

function getChapters(){
	var arr=[];
	var func = function(key, val){
		arr.push( $(val).text().toLowerCase().capitalize());
	}
	$('h2').each(func);
	
	if(arr.length == 0){
		$('h1').each(func);
	}
	window.HtmlViewer.getChapters(JSON.stringify(arr));
}


function trans(key,val){
	$(val).html(language[$(val).html()]);
}

function uppcase(key,val){
	$(val).html($(val).html().toUpperCase());
}
function translate(code,func){
	//alert(code);
	lang = code;
	
	if(lang == null || lang == ''){
		capitalizeEachWord('h2',func);
		return;
	}
	getScript('file:///android_asset/language.'+code+'.js',function(){
	//getScript('../language.'+code+'.js',function(){
		if(typeof(language) != "undefined"){
			var tags=["h1","h2"];
			$.each(tags,function(key,val){
				$(val).each(function(key1,val1){
					trans(key1,val1);
					uppcase(key1,val1);
				});
				
			});
			$('h3').each(trans);
			$('img[src*=en]').each(function(key,val){
				$(val).attr('src',$(val).attr('src').replace('en',lang));
			});
			capitalizeEachWord('h2',func);
		}
	},function(){
		capitalizeEachWord('h2',func);
		console.log('error via everything else');
	});
}
function getHtmlParentImage(fullname){
	var img = fullname.substring(fullname.lastIndexOf('/')+1 ,fullname.length);
	$img = $('img[src="' + img + '"]');
	var path = fullname.substring(0,fullname.lastIndexOf('/')+1)
	$img.parent().find('img').each(function(key,val){
		var src = $(this).attr('src');
		if(lang != null && lang != '')
			src = src.replace(lang,"en");
		$(this).attr('src',path + src);	
	});
	var parentHTML = $img.parent().html();
	parentHTML = parentHTML.replace(/[\n\r]/g, "");
	var $div = $('#clone');
	$div.html(parentHTML);
	
	var tags=["h1","h2","h3"];
		$.each(tags,function(key,val){
			$(val).each(function(key1,val1){
				var $obj = $div.find(val1);
				$obj.html($obj.attr('key'));
			});
		});
	
	window.HtmlViewer.getHTML($div.html());
	//alert($div.html());
	$img.attr('src', img);
	$div.empty();
}

function removeFavorite(fullname){
	$img = $('img[src="' + fullname + '"]');
	$img.parent().remove();
	window.HtmlViewer.getAllHTML($('html')[0].outerHTML);
}

function searchQuery(key){
	if(key == null || key == ''){
		$('h1').show();
		$('div').show();
	}else{
		$('h1').hide();
		$('div').hide();
		
		$( "div:contains('"+ key +"')" ).show();
	}
}

function removeUnicode(str){
	str= str.toLowerCase();
	str= str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g,"a");
	str= str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g,"e");
	str= str.replace(/ì|í|ị|ỉ|ĩ/g,"i");
	str= str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g,"o");
	str= str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g,"u");
	str= str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g,"y");
	str= str.replace(/đ/g,"d");
	str= str.replace(/!|@|\$|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\'| |\"|\&|\#|\[|\]|~/g,"-");
	str= str.replace(/-+-/g,"-"); //thay thế 2- thành 1-
	str= str.replace(/^\-+|\-+$/g,"");//cắt bỏ ký tự - ở đầu và cuối chuỗi
	return str;
}


jQuery.expr[':'].contains = function(a, i, m) {
	var x = removeUnicode(jQuery(a).text());
	var y = removeUnicode(m[3]);
	return x.indexOf(y) >= 0;
  //return jQuery(a).text().toUpperCase()
    //  .indexOf(m[3].toUpperCase()) >= 0;
};

function getScript(url, success,fail) {
	var script = document.createElement('script');
	script.src = url;
	var head = document.getElementsByTagName('head')[0],
		done = false;
	// Attach handlers for all browsers
	script.onload = script.onreadystatechange = function() {
	  if (!done && (!this.readyState
		   || this.readyState == 'loaded'
		   || this.readyState == 'complete')) {
		done = true;
		success();
		script.onload = script.onreadystatechange = null;
		head.removeChild(script);
	  }
	};
	script.onerror = function() {
		fail();
	}
	head.appendChild(script);
}

String.prototype.capitalize = function(){
   return this.replace( /(^|\s)([a-z|đ|ứ|á])/g , function(m,p1,p2){ 	return p1+p2.toUpperCase();  } );
};